//
//  RootViewController.m
//  weibo3
//
//  Created by Tian Wu on 11-4-8.
//  Copyright 2011年 nfsysu. All rights reserved.
//

#import "RootViewController.h"
#import "HttpMethod.h"
#import "Base64.h"
#import "JsonStatusParser.h"
#import "StringPart.h"
#import "FilePart.h"
#import "LoginWindow.h"
#import "StatusTableDelegate.h"
#import "StatusCell.h"
#import "weibo3AppDelegate.h"
#import "OARequestParameter.h"

#define LISTVIEW_CELL_IDENTIFIER		@"StatusCell"

extern weibo3AppDelegate *appDelegate;
extern NSString * callbackURL;
extern RootViewController *rootView;


@implementation RootViewController

@synthesize publicData , imgURL ,currentUser , thumbData , listView, cacheManager;

NSString *baseUrl = @"http://api.t.sina.com.cn/";
NSString *_consumerKey = @"83996567";
NSString * error = @"error_code";


#pragma mark -
#pragma mark Init/Dealloc

-(id) init{
    if (rootView != nil) {
        return rootView;
    }
    self= [super initWithWindowNibName:@"MainView"];
	if(self != nil){
                
        client = [[HttpClient alloc] init];
        cacheManager = [[TimelineCacheManager alloc] init];
        viewimage = [[ViewImage alloc] init];
        NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
        [nc addObserver:self 
               selector:@selector(scrollDownARow) 
                   name:@"scrollDownARow"
                 object:nil];
        [nc addObserver:self 
               selector:@selector(scrollUpARow) 
                   name:@"scrollUpARow"
                 object:nil];
        [nc addObserver:self 
               selector:@selector(viewImageInCurrentRow) 
                   name:@"viewDetail"
                 object:nil];
        
        rootView = self;
                
	}
	return self;
}

- (void) initUserDefaults{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults stringForKey:@"AutoRefresh"] == nil ) {
        [defaults setObject:@"ON" forKey:@"AutoRefresh"];
    }
    if ([defaults stringForKey:@"displayNotif"] == nil ) {
        [defaults setObject:@"ON" forKey:@"displayNotif"];
    }
    if ([defaults stringForKey:@"statusNotif"] == nil ) {
        [defaults setObject:@"OFF" forKey:@"statusNotif"];
    }
    if ([defaults stringForKey:@"commentNotif"] == nil ) {
        [defaults setObject:@"ON" forKey:@"commentNotif"];
    }
    if ([defaults stringForKey:@"mentionNotif"] == nil ) {
        [defaults setObject:@"ON" forKey:@"mentionNotif"];
    }
    if ([defaults stringForKey:@"dmNotif"] == nil ) {
        [defaults setObject:@"ON" forKey:@"dmNotif"];
    }
    if ([defaults stringForKey:@"followerNotif"] == nil ) {
        [defaults setObject:@"ON" forKey:@"followerNotif"];
    }
    
    
    /*
    if ([defaults stringForKey:@"lastMentionId"] == nil) {
        
        [defaults setObject:[NSString stringWithFormat:@"0"] forKey:@"lastMentionId"];
    }
    if ([defaults stringForKey:@"lastCommentId"] == nil) {
        [defaults setObject:[NSString stringWithFormat:@"0"] forKey:@"lastCommentId"];
    }
     */
    
}

-(void) awakeFromNib{
    before = YES;
    //[tabTable selectRowIndexes:[NSIndexSet indexSetWithIndex:0] byExtendingSelection:YES];
    [blueDotTable deselectAll:self];
    [[myFans cell] setBackgroundStyle:NSBackgroundStyleRaised];
    dockTile = [NSApp dockTile];
    
    
    
    
    [self initUserDefaults];
}


#pragma mark -
#pragma mark CustomInit

- (void) loginInit{
    
    
    self.currentUser = [self verifyUser];
    [theWindow setTitle:[self.currentUser screen_name]];
    NSImage *image = [[NSImage alloc] initWithContentsOfURL:[NSURL URLWithString:[self.currentUser profile_image_url]]];
    [myProfileImage setImageScaling:NSScaleToFit];
    [myProfileImage setImage:image];
    [image release];
    [myFans setTitleWithMnemonic:[NSString stringWithFormat:@"关注:%d  粉丝:%d  微博:%d",[self.currentUser friends_count],[self.currentUser followers_count],[self.currentUser statuses_count]]];
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"logined"];
    
    //[self refreshStatusWithFunction:0 Page:1]; 
	[self refreshStatusWithFunction:0 Page:1]; 

}

#pragma mark -
#pragma mark WindowControllerMethod

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{
    
    
    
}

-(void) windowDidLoad{
    
    
}

- (void) refreshAutomatic{
    
    
    
}

- (void)windowDidBecomeKey:(NSNotification *)notification{
    if(![myEditController wasCancelled]){
        if([tabTable selectedRow] != 4 && [[[NSUserDefaults standardUserDefaults] stringForKey:@"AutoRefresh"] isEqualToString:@"ON"] && [[self.publicData objectAtIndex:0] text] != nil){
            [self refreshStatusWithFunction:[tabTable selectedRow] Page:[page intValue]]; 
        }
        else if([[self.publicData objectAtIndex:0] text] == nil){
            if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"accessTokenKey"] length] > 0) {
				[self loginInit];
				
			}
        }
        else{
            [listView deselectRows];
        }
   }
}

#pragma mark -
#pragma mark UtilMethod

- (NSString *) generateParameterString:(NSDictionary *) parameters{
	NSMutableString * result = [[NSMutableString alloc] init];
    int i = 0;
	for(NSString * key in parameters){
		NSString * value = [parameters objectForKey:key];
		if(value != nil){
            if(i == 0){
                [result appendString:@"?"];
            }
            else{
                [result appendString:@"&"];
            }
            i++;
			[result appendFormat:@"%@=%@",key,value];
		}
	}
	return result;
}

- (void) generateBodyDic:(NSMutableDictionary *) bodyDic paraKey:(NSString *) key paraValue:(NSString *) value{
	if(value!=nil){
		[bodyDic setObject:value forKey:key];
	}
}

- (NSDictionary *) setAuth{
	[Base64 initialize];
	NSMutableString * tmpString = [[NSMutableString alloc]init];
    
	[tmpString appendFormat:[[NSUserDefaults standardUserDefaults] stringForKey:@"username"]];
	[tmpString appendFormat:@":"];
	[tmpString appendFormat:[[NSUserDefaults standardUserDefaults] stringForKey:@"password"]];
	NSData* data=[tmpString dataUsingEncoding:NSUTF8StringEncoding];
	NSString * baseString = [Base64 encode:data];
	NSString * authString = [[NSString alloc] initWithFormat:@"%@ %@",@"Basic",baseString];
	NSDictionary * headers = [NSDictionary dictionaryWithObjectsAndKeys:authString,@"Authorization",nil];
	[authString release];
	[tmpString release];
	return headers;
    
    
}

- (NSDictionary *) setAuthWithURL:(NSString *) urlString HttpMethod:(methodEnum) methodE  Parameters:(NSMutableDictionary *) parameters{
    
    
    accessToken = [[OAToken alloc] init];
    
    accessToken.key = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessTokenKey"];
    accessToken.secret = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessTokenSecret"];
    accessToken.verifier = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessTokenVerifier"];
    OAConsumer *consumer = [[OAConsumer alloc] initWithKey:_consumerKey
													secret:@"d3ae350c39c5f12be40e4c7fc389266d"];
    
	
	OauthSingnature *request = [[OauthSingnature alloc] initWithURL:urlString
                                                           consumer:consumer
                                                              token:accessToken
                                                              realm:nil
                                                  signatureProvider:nil];
    
    
    NSArray * values = [parameters allValues];
    NSArray * keys = [parameters allKeys];
    NSMutableArray * parameter = [[NSMutableArray alloc] init];
    for (int i=0; i < [values count]; i++) {
        OARequestParameter * requestParameter = [OARequestParameter requestParameterWithName:[keys objectAtIndex:i] value:[values objectAtIndex:i]];
        [parameter addObject:requestParameter];
    }
    
    [request setParameters:parameter];
	[request setMethod:methodE];
    [request setUrlStringWithoutQuery:[[urlString componentsSeparatedByString:@"?"] objectAtIndex:0]];
    
    NSString *authString = [request getSingnatureString];
    NSDictionary * headers = [NSDictionary dictionaryWithObjectsAndKeys:authString,@"Authorization",nil];
    
    return headers;
    
}

- (NSString *) retrieveData:(NSString *) urlString callMethod:(methodEnum ) methodE body:(NSDictionary *) httpbody{
	NSURL * url = [[NSURL alloc] initWithString:urlString];
	HttpMethod * method = [[HttpMethod alloc] initWithMethod:methodE];
	[method setUrl:url];
    NSMutableDictionary *tempBody = [NSMutableDictionary dictionaryWithDictionary:httpbody];
	NSDictionary * headers = [self setAuthWithURL:urlString HttpMethod:methodE Parameters:tempBody];
	[method setHeaderFieldsWithDictionary:headers];
	[method setBodyWithDictionary:httpbody]; 
	HttpResponse * response =[client executeMethod:method];
	[url release];
	[method release];
	return [response responseString];    
}

-(NSString * ) uploadData:(NSString *) status url:(NSString *) urlString picture:(NSString *) pic lat:(double ) lat log:(double) log{
	NSURL * url = [[NSURL alloc] initWithString:urlString];
	HttpMethod * method = [[HttpMethod alloc] initWithMethod:MULTI];
	StringPart * statusPart = [[StringPart alloc] initWithParameter:status withName:@"status"];
    pic = [pic stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
	NSURL * picUrl = [NSURL URLWithString:pic];
    
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:status,@"status", nil];
    
	FilePart * picPart = [[FilePart alloc] initWithNameAndFile:@"pic" file:picUrl];
	[method addPart:statusPart];
	[method addPart:picPart];
	if(lat != nilLatitude){
		StringPart * latPart = [[StringPart alloc] initWithParameter:[[[NSString alloc] initWithFormat:@"%f",lat] autorelease] withName:@"latitude"];
        [paraDic setValue:[[NSString alloc] initWithFormat:@"%f",lat] forKey:@"lat"];
		[method addPart:latPart];
		[latPart release];
	}
	if(log != nilLongitude){
		StringPart * logPart = [[StringPart alloc] initWithParameter:[[[NSString alloc] initWithFormat:@"%f",log] autorelease] withName:@"longitude"];
        [paraDic setValue:[[NSString alloc] initWithFormat:@"%f",log] forKey:@"long"];
		[method addPart:logPart];
		[logPart release];
	}	
	[method setUrl:url];
	NSDictionary * headers = [self setAuthWithURL:urlString HttpMethod:POST Parameters:paraDic];
	[method setHeaderFieldsWithDictionary:headers];
	
	HttpResponse * response =[client executeMethod:method];
	[url release];
	[method release];
	return [response responseString];
}

- (User *)verifyUser{
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"account/verify_credentials.json"];
	NSString * resultString = [self retrieveData:urlString callMethod:GET body:nil];
	User *my = [JsonStatusParser parseToUsers:resultString];
	[urlString release];
	[my autorelease];
	[resultString release];
	return my;
}

- (void) refreshFans{
    self.currentUser = [self verifyUser];
    [myFans setTitleWithMnemonic:[NSString stringWithFormat:@"关注:%d  粉丝:%d  微博:%d",[self.currentUser friends_count],[self.currentUser followers_count],[self.currentUser statuses_count]]];
    
}

- (Status *)statusAtIndexRow:(NSInteger) row{
    return [self.publicData objectAtIndex:row];
}


#pragma mark -
#pragma mark GetStatusMethod



- (NSArray *)getUserTimeline:(weiboId) uid userId:(int) userId screenName:(NSString *) screenName 
                     sinceId:(weiboId) sinceId maxId:(weiboId) maxid count:(int) maxCount page:(int) currentPage{
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	// uid will lost at here temporarily
	[urlString appendFormat:@"statuses/user_timeline.json"];
    NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:
							  [NSString stringWithFormat:@"%lld",userId],@"user_id",
							  [NSString stringWithFormat:@"%lld",sinceId],@"since_id",
							  [NSString stringWithFormat:@"%lld",maxid],@"max_id",
							  [NSString stringWithFormat:@"%d",maxCount],@"count",
							  [NSString stringWithFormat:@"%d",currentPage],@"page",nil];
	NSString * paraString = [self generateParameterString:paraDic];
	[urlString appendString:paraString];
	NSString * resultString = [self retrieveData:urlString callMethod:GET body:paraDic];
	NSArray * result = [JsonStatusParser parseToStatuses:resultString];
	[urlString release];
	[result autorelease];
	[resultString release];
	return result;		
}

- (UnreadCount *)getUnreadCountSinceId:(weiboId) since_id includeNewStatus:(int) with_new_status{
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/unread.json"];
	NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:
							  [NSString stringWithFormat:@"%d",with_new_status],@"with_new_status",
							  [NSString stringWithFormat:@"%lld",since_id],@"since_id",nil];
	NSString * paraString = [self generateParameterString:paraDic];
	[urlString appendFormat:@"%@",paraString];
	NSString * resultString = [self retrieveData:urlString callMethod:GET body:paraDic];
	UnreadCount * result = [JsonStatusParser parseToUnreadCount:resultString];
	[urlString release];
	[result autorelease];
	[resultString release];
	return result;		
}

- (NSArray *)getCommentsTimeline:(weiboId) sinceId maxId:(weiboId) maxid count:(int) maxCount page:(int) currentPage{
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/comments_timeline.json"];
	NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:
							  [NSString stringWithFormat:@"%lld",sinceId],@"since_id",
							  [NSString stringWithFormat:@"%lld",maxid],@"max_id",
							  [NSString stringWithFormat:@"%d",maxCount],@"count",
							  [NSString stringWithFormat:@"%d",currentPage],@"page",nil];
	NSString * paraString = [self generateParameterString:paraDic];
	[urlString appendFormat:@"%@",paraString];
	NSString * resultString = [self retrieveData:urlString callMethod:GET body:paraDic];
	NSArray * result = [JsonStatusParser parseToComments:resultString];
	[urlString release];
	[result autorelease];
	[resultString release];
	return result;			
}

- (NSArray *)getCommentsToMe:(weiboId) sinceId maxId:(weiboId) maxid count:(int) maxCount page:(int) currentPage{
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/comments_to_me.json"];
	NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:
							  [NSString stringWithFormat:@"%lld",sinceId],@"since_id",
							  [NSString stringWithFormat:@"%lld",maxid],@"max_id",
							  [NSString stringWithFormat:@"%d",maxCount],@"count",
							  [NSString stringWithFormat:@"%d",currentPage],@"page",nil];
	NSString * paraString = [self generateParameterString:paraDic];
	[urlString appendFormat:@"%@",paraString];
	NSString * resultString = [self retrieveData:urlString callMethod:GET body:paraDic];
	NSArray * result = [JsonStatusParser parseToComments:resultString];
	[urlString release];
	[result autorelease];
	[resultString release];
	return result;			
}

- (NSArray *)getComments:(weiboId) statusId count:(int) maxCount page:(int) currentPage{
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/comments.json"];
    NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:
							  [NSString stringWithFormat:@"%lld",statusId],@"id",
							  [NSString stringWithFormat:@"%d",maxCount],@"count",
							  [NSString stringWithFormat:@"%d",currentPage],@"page",
							  nil];
	NSString * paraString = [self generateParameterString:paraDic];
	[urlString appendFormat:@"%@",paraString];
	NSString * resultString = [self retrieveData:urlString callMethod:GET body:paraDic];
	NSArray * result = [JsonStatusParser parseToStatuses:resultString];
	[urlString release];
	[result autorelease];
	[resultString release];
	return result;				
}

- (NSArray *)getEmotionsArrayWithCount:(int) count{
    
    NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"emotions.json"];
    NSString * resultString = [self retrieveData:urlString callMethod:GET body:nil];
    NSArray * result = [JsonStatusParser parseToDictionaryArrayWithString:resultString];
    
    result = [result subarrayWithRange:NSMakeRange(0, count - 1)];
    
    return result;

}


- (NSArray *)getPublicTimeline:(int) count{
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/public_timeline.json"];
	NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",count],@"count",nil];
    NSString * paraString = [self generateParameterString:paraDic];
    [urlString appendString:paraString];
	NSString * resultString = [self retrieveData:urlString callMethod:GET body:paraDic];
	NSArray * result = [JsonStatusParser parseToStatuses:resultString];
	[urlString release];
	[result autorelease];
	[resultString release];
	return result;
}

- (NSArray *)getMentions:(weiboId) sinceId maxId:(weiboId) maxid count:(int) maxCount page:(int) currentPage{
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/mentions.json"];
    NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%lld",sinceId],@"since_id",[NSString stringWithFormat:@"%lld",maxid],@"max_id",[NSString stringWithFormat:@"%d",maxCount],@"count",[NSString stringWithFormat:@"%d",currentPage],@"page",nil];
    NSString * paraString = [self generateParameterString:paraDic];
    [urlString appendString:paraString];
	NSString * resultString = [self retrieveData:urlString callMethod:GET body:paraDic];
	NSArray * result = [JsonStatusParser parseToStatuses:resultString];
	[urlString release];
	[result autorelease];
	[resultString release];
	return result;			
}


- (NSArray *)getFriendsTimeline:(weiboId) sinceId maxId:(weiboId) maxid count:(int) maxCount page:(int) currentPage{
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/friends_timeline.json"];
	NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%lld",sinceId],@"since_id",[NSString stringWithFormat:@"%lld",maxid],@"max_id",[NSString stringWithFormat:@"%d",maxCount],@"count",[NSString stringWithFormat:@"%d",currentPage],@"page",nil];
    NSString * paraString = [self generateParameterString:paraDic];
    [urlString appendString:paraString];
    NSString * resultString = [self retrieveData:urlString callMethod:GET body:paraDic];
	NSArray * result = [JsonStatusParser parseToStatuses:resultString];
	[urlString release];
	[result autorelease];
	[resultString release];
	return result;	
}


#pragma mark -
#pragma mark PostStatusMethod



- (Status *)statusUpdate:(NSString *) status inReplyToStatusId:(weiboId) replyToId latitude:(double) lat longitude:(double) longitude{
	/*
    if(status == nil){
		InvalidParameterException * exception = [InvalidParameterException 
												 exceptionWithName:@"Invalid Parameter Exception" reason:@"Status should not be nil. " userInfo:nil];
		@throw exception;
	}
     */
    NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/update.json"];
	NSMutableDictionary * mbody = [[NSMutableDictionary alloc] init];
	[mbody setObject:status forKey:@"status"];
	if(replyToId!=nilReplyId)
        [self generateBodyDic:mbody paraKey:@"in_reply_to_status_id" paraValue:[NSString stringWithFormat:@"%llu",replyToId]];
	if(lat != nilLatitude)
        [self generateBodyDic:mbody paraKey:@"lat" paraValue:[NSString stringWithFormat:@"%f",lat] ];
	if(longitude != nilLongitude)
        [self generateBodyDic:mbody paraKey:@"long" paraValue:[NSString stringWithFormat:@"%f",longitude] ];
	NSString * resultString = [self retrieveData:urlString callMethod: POST body:mbody];
    NSLog(@"respond:%@",resultString);
	NSRange range = [resultString rangeOfString:error];
	if(range.location == NSNotFound){
		Status * result = [JsonStatusParser parseToStatus:resultString];
		[urlString release];
		[result autorelease];
		[resultString release];
		[mbody release];
        [[NSSound soundNamed:@"sentweibo.aif"] play];
        
		return result;	
	}else{
		[urlString release];
		[resultString release];
		[mbody release];        
        
        NSAlert *alert = [NSAlert alertWithMessageText:@"发送失败" defaultButton:@"好的" alternateButton:nil otherButton:nil informativeTextWithFormat:@"发送失败！请检查微博内容。"];
        [alert runModal];
        return NULL;
	}
}

- (Status *)statusUpload:(NSString *) status pic:(NSString *) pic latitude:(double ) latitude longitude:(double) longitude{
	/*
    if(status == nil){
		InvalidParameterException * exception = [InvalidParameterException 
												 exceptionWithName:@"Invalid Parameter Exception" reason:@"Status should not be nil. " userInfo:nil];
		@throw exception;
	}
     */
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/upload.json"];
	NSString * resultString = [self uploadData:status url:urlString picture:pic lat:latitude log:longitude];
    
    
	NSRange range = [resultString rangeOfString:error];
	if(range.location == NSNotFound){
		Status * result = [JsonStatusParser parseToStatus:resultString];
		[urlString release];
		[result autorelease];
		[resultString release];
        
        [[NSSound soundNamed:@"sentweibo.aif"] play];
		return result;	
	}else{
		[urlString release];
		[resultString release];
        NSAlert *alert = [NSAlert alertWithMessageText:@"发送失败" defaultButton:@"好的" alternateButton:nil otherButton:nil informativeTextWithFormat:@"发送失败！请检查微博内容。"];
        [alert runModal];
        return NULL;
	}
}

- (Status *)statusDestroy:(weiboId) statusId{
    /*
	if(statusId<0){
		InvalidParameterException * exception = [InvalidParameterException 
												 exceptionWithName:@"Invalid Parameter Exception" reason:@"Status should not be nil. " userInfo:nil];
		@throw exception;		
	}
     */
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/destroy/%lld.json",statusId];
	NSString * resultString = [self retrieveData:urlString callMethod:POST body:nil];
	Status * result = [JsonStatusParser parseToStatus:resultString];
	[urlString release];
	[result autorelease];
	[resultString release];
	return result;							
}

- (void)resetCountWithType:(int) type{
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/reset_count.json"];
	NSDictionary * mbody = [NSDictionary 
                            dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",type],@"type",nil];
    
	NSString * resultString = [self retrieveData:urlString callMethod: POST body:mbody];
	[resultString release];
}

- (Status *)statusRepost:(weiboId) statusId status:(NSString *) status isComment:(int) withComment{
    /*
	if(status == nil||statusId<=0){
		InvalidParameterException * exception = [InvalidParameterException 
												 exceptionWithName:@"Invalid Parameter Exception" reason:@"Status should not be nil. " userInfo:nil];
		@throw exception;
	}
     */
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/repost.json"];
	NSDictionary * mbody = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%lld",statusId],@"id",status,@"status",[NSString stringWithFormat:@"%d",withComment],@"is_comment",nil];
	NSString * resultString = [self retrieveData:urlString callMethod: POST body:mbody];
	Status * result = [JsonStatusParser parseToStatus:resultString];
	[urlString release];
	[result autorelease];
	[resultString release];
	return result;		
}

- (void) comment:(weiboId) statusId commentString:(NSString *) commentString{
    /*
	if(statusId == nil||commentString==nil){
		InvalidParameterException * exception = [InvalidParameterException 
												 exceptionWithName:@"Invalid Parameter Exception" reason:@"Status should not be nil. " userInfo:nil];
		@throw exception;
	}
     */
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/comment.json"];
	//todo add new check
    
	NSDictionary * mbody = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%lld",statusId],@"id",commentString,@"comment",nil];
	NSString * resultString = [self retrieveData:urlString callMethod:POST body:mbody];
	//[JsonStatusParser parseToComment:resultString];
	[urlString release];
	//[result autorelease];
	[resultString release];
	//return result;					
}

- (WComment *)statusReply:(weiboId ) statusId commentId:(weiboId ) commentId comment:(NSString *) comment{
    /*
    if(commentId == 0||comment==nil){
		InvalidParameterException * exception = [InvalidParameterException 
												 exceptionWithName:@"Invalid Parameter Exception" reason:@"Status should not be nil. " userInfo:nil];
		@throw exception;
	}
     */
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/comment.json"];
	//todo add new check
    
	NSDictionary * mbody = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%lld",statusId],@"id",[NSString stringWithFormat:@"%lld",commentId],@"cid",comment,@"comment",nil];
	NSString * resultString = [self retrieveData:urlString callMethod:POST body:mbody];
    NSLog(@"comment result: %@",resultString);
	//[JsonStatusParser parseToComment:resultString];
	[urlString release];
	//[result autorelease];
	[resultString release];
	//return result;	
    
    return nil;
    
}

- (BOOL)requestRequestToken{
    // Get Singnature Header Start 
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"oauth/request_token"];    
    OAConsumer *consumer = [[OAConsumer alloc] initWithKey:@"83996567"
													secret:@"d3ae350c39c5f12be40e4c7fc389266d"];
	OauthSingnature *request = [[OauthSingnature alloc] initWithURL:urlString
                                                           consumer:consumer
                                                              token:nil
                                                              realm:nil
                                                  signatureProvider:nil];
	[request setMethod:POST];
	
   
    NSString * queryString = [request getQueryString];
    [urlString appendFormat:@"?%@",queryString];
    
    
    NSURL * url = [[NSURL alloc] initWithString:urlString];
    
    HttpMethod * method = [[HttpMethod alloc] initWithMethod:POST];
	[method setUrl:url];
    HttpResponse * response =[client executeMethod:method];
	[url release];
	[method release];
    
    NSString *responseBody = [[NSString alloc] initWithData:[response responseData]
                                                   encoding:NSUTF8StringEncoding];

    accessToken = [[OAToken alloc] initWithHTTPResponseBody:responseBody];
    if (accessToken.secret != nil) {
        return YES;
    }
    return NO;
}
         
- (void) askUserForAuthorization{
             
    NSString *address = [NSString stringWithFormat:
                         @"http://api.t.sina.com.cn/oauth/authorize?oauth_token=%@",
                         accessToken.key];
    //return address;  //handle open url
    
    if( myEditController == nil){
        myEditController = [[LoginWindow alloc] init];
    }
    
    before = NO;
	[myEditController edit:address from:self];
	if (![myEditController wasCancelled]){
		//[[NSUserDefaults standardUserDefaults] setObject:pin forKey:@"accessTokenVerifier"];
        //[self requestAccessToken];
	}
    else{
        if([[[NSUserDefaults standardUserDefaults] stringForKey:@"accessTokenVerifier"] length] == 0){
            [NSApp terminate:nil]; 
        }
    }
    
}

- (void)requestAccessToken{
    
    
    
    NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"oauth/access_token"];    
    NSURL * url = [[NSURL alloc] initWithString:urlString];
	HttpMethod * method = [[HttpMethod alloc] initWithMethod:POST];
	[method setUrl:url];
        
    OAConsumer *consumer = [[OAConsumer alloc] initWithKey:@"83996567"
													secret:@"d3ae350c39c5f12be40e4c7fc389266d"];
    accessToken.verifier = [[NSUserDefaults standardUserDefaults] stringForKey:@"accessTokenVerifier"];
    	
	OauthSingnature *request = [[OauthSingnature alloc] initWithURL:urlString
                                                           consumer:consumer
                                                              token:accessToken
                                                              realm:nil
                                                  signatureProvider:nil];
	
	[request setMethod:POST];
    
    NSString * headerString = [request getSingnatureString];
    
    NSMutableDictionary *headers = [NSMutableDictionary dictionaryWithObject:headerString forKey:@"Authorization"];
    
	[method setHeaderFields:headers];
    
	HttpResponse * response =[client executeMethod:method];
	[url release];
	[method release];
    
    NSString *responseBody = [[NSString alloc] initWithData:[response responseData]
                                                   encoding:NSUTF8StringEncoding];    
    accessToken = [[OAToken alloc] initWithHTTPResponseBody:responseBody];
    
    [[NSUserDefaults standardUserDefaults] setObject:accessToken.key forKey:@"accessTokenKey"];
    [[NSUserDefaults standardUserDefaults] setObject:accessToken.secret forKey:@"accessTokenSecret"];
    
    //start using.
    
    [cacheManager resetAllCaches];
    [self loginInit];
    
}


#pragma mark -
#pragma mark CustomExternMethod

- (void) checkForNewStatus{
    
    /*
    Status *temp = [[self getMentions:0 maxId:0 count:1 page:1] objectAtIndex:0];
    if ([temp aid] > [[[NSUserDefaults standardUserDefaults] stringForKey:@"lastMentionId"] longLongValue]) {
        [blueDotTable selectRowIndexes:[NSIndexSet indexSetWithIndex:1] byExtendingSelection:YES];
        [[NSSound soundNamed:@"getTimeline.aif"] play];
    }
    else{
        [blueDotTable deselectRow:1];
    }
    WComment *comment = [[self getCommentsToMe:0 maxId:0 count:1 page:1] objectAtIndex:0];
    if ([comment aid] > [[[NSUserDefaults standardUserDefaults] stringForKey:@"lastCommentId"] longLongValue]) {
        [blueDotTable selectRowIndexes:[NSIndexSet indexSetWithIndex:3] byExtendingSelection:YES];
        [[NSSound soundNamed:@"getTimeline.aif"] play];
    }
    else{
        [blueDotTable deselectRow:3];
    }*/
    
    [self didBackgroundCheck];
    
}

- (BOOL) didBackgroundCheck{
        
    NSString * badgeLabel = [NSString stringWithString:@""];
    int lableNumber = 0;
    
    UnreadCount *count = [self getUnreadCountSinceId:[cacheManager.lastFollowingStatusID longLongValue] includeNewStatus:1];
    
    if (count.mentions > 0) {
        [blueDotTable selectRowIndexes:[NSIndexSet indexSetWithIndex:1] byExtendingSelection:YES];
    }
    else{
        [blueDotTable deselectRow:1];
    }
    
    if (count.comments > 0) {
        [blueDotTable selectRowIndexes:[NSIndexSet indexSetWithIndex:3] byExtendingSelection:YES];
    }
    else{
        [blueDotTable deselectRow:3];
    }
    
    [appDelegate changeStatusItemTo:NO];
    
    if (count.comments > 0 || count.mentions > 0 || count.new_status > 0 || count.dm > 0 || count.followers > 0){
        
        NSMenu * menu = [[NSMenu alloc] initWithTitle:@"新消息"];
        if (count.new_status > 0) {
            [menu addItemWithTitle:@"新微博" action:@selector(viewAndRefreshStatus) keyEquivalent:@""];
            if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"statusNotif"] isEqualToString:@"ON"]) {
                [appDelegate changeStatusItemTo:YES];
                badgeLabel = [NSString stringWithString:@"微博"];
                [NSApp requestUserAttention: NSInformationalRequest];
            }
            
        }
        if (count.mentions > 0) {
            [menu addItemWithTitle:[NSString stringWithFormat:@"新提到我:%d条",count.mentions] action:@selector(viewAndRefreshMentions) keyEquivalent:@""];
            if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"mentionNotif"] isEqualToString:@"ON"]) {
                [appDelegate changeStatusItemTo:YES];
                lableNumber += count.mentions;
            }
        }
        if (count.comments > 0) {
            [menu addItemWithTitle:[NSString stringWithFormat:@"新评论:%d条",count.comments] action:@selector(viewAndRefreshComments) keyEquivalent:@""];
            if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"commentNotif"] isEqualToString:@"ON"]) {
                [appDelegate changeStatusItemTo:YES];
                lableNumber += count.comments;
            }
        }
        if (count.dm > 0) {
            [menu addItemWithTitle:[NSString stringWithFormat:@"新私信:%d条",count.dm] action:@selector(directToDM) keyEquivalent:@""];
            if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"dmNotif"] isEqualToString:@"ON"]) {
                [appDelegate changeStatusItemTo:YES];
            }
        }
        if (count.followers > 0) {
                [menu addItemWithTitle:[NSString stringWithFormat:@"新粉丝:%d个",count.followers] action:@selector(directToFollower) keyEquivalent:@""];
                if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"followerNotif"] isEqualToString:@"ON"]) {
                    [appDelegate changeStatusItemTo:YES];
            }
        }
        
        
        if (lableNumber > 0) {
            badgeLabel = [NSString stringWithFormat:@"%d",lableNumber];
            [NSApp requestUserAttention: NSInformationalRequest];
        }
        [dockTile setBadgeLabel:badgeLabel];
        [dockTile display];

        [[appDelegate statusItem] setMenu:menu];
        
        [menu autorelease];
        
        return YES;
    }
    else{
        [[appDelegate statusItem] setMenu:nil];
        [appDelegate changeStatusItemTo:NO];
        [dockTile setBadgeLabel:nil];
        [dockTile display];
        return NO;
        
    }
    
}


- (IBAction) showPreference:(id)sender{
    if (!preferenceWindow) {
        preferenceWindow = [[PreferenceController alloc] init];
    }
    [preferenceWindow showWindow:self];
}

- (IBAction) newWeibo:(id)sender{
    if(!newTweetWindow){
        newTweetWindow = [[newTweet alloc] init];
    }
    [newTweetWindow edit:nil from:self];
}

- (void) viewImageInRow:(NSInteger) row{
    if(!viewimage){
        viewimage = [[ViewImage alloc] init];
    }
    [viewimage edit:[self.publicData objectAtIndex:row] from:self];
}

- (void) replyCommentInRow:(NSInteger) row{
    if(!newTweetWindow){
        newTweetWindow = [[newTweet alloc] init];
    }
    [newTweetWindow didReplyToComment:[self.publicData objectAtIndex:row] from:self];
    [self refreshStatus:3];    
}

- (IBAction) didLogin: (id) sender{
    
    if ([self requestRequestToken]) {
        [self askUserForAuthorization];
    }
    
}

- (IBAction) sendWeibo:(id)sender{
    NSString *status = [textField stringValue];
    
    if (imgURL == NULL) {
        [self statusUpdate:status inReplyToStatusId:nilReplyId latitude:nilLatitude longitude:nilLongitude];
    }
    else{
        
        [self statusUpload:status pic:self.imgURL latitude:nilLatitude longitude:nilLongitude];
        self.imgURL = NULL;
    }
}

- (IBAction) selectImg: (id) sender{
    
    NSOpenPanel *attachmentPanel = [NSOpenPanel openPanel];
    [attachmentPanel setAllowsMultipleSelection:false];
    [attachmentPanel setCanChooseFiles:YES];
    [attachmentPanel setCanChooseDirectories:FALSE];
    if ( [attachmentPanel runModalForDirectory:nil file:nil] == NSOKButton )
    {
        // Get an array containing the full filenames of all
        // files and directories selected.
        NSArray* files = [attachmentPanel filenames];
        
        
        self.imgURL = [NSString stringWithFormat:@"file://%@",[files objectAtIndex:0]];
    }
}




- (void) refreshStatus: (NSInteger) function{
    [progress startAnimation:nil];
    _tabTable.isUserViewMode = NO;
    for (int i=0; i<5; i++) {
        if(function == 0){
            self.publicData = [self getFriendsTimeline:0 maxId:0 count:20 page:1];
        }
        else if(function == 1){
            self.publicData = [self getMentions:0 maxId:0 count:20 page:1];
        }
        else if(function == 2){
            self.publicData = [self getUserTimeline:0 userId:0 screenName:nil sinceId:0 maxId:0 count:20 page:1];
        }
        else if(function == 3){
            self.publicData = [self getCommentsTimeline:0 maxId:0 count:20 page:1];
        }
        else{
            self.publicData = [self getPublicTimeline:20];
        }
        
        if([self.publicData count] == 0){
            NSLog(@"%d try,getError!",i+1);
        }
        else{
            break;
        }
        
    }
    
    
    
    
    if([self.publicData count] == 0){
        NSAlert *alert = [NSAlert alertWithMessageText:@"发生了一点错误" defaultButton:@"知道了" alternateButton:nil otherButton:nil informativeTextWithFormat:@"获取数据超时！",nil];
        [alert runModal];
        [alert autorelease];
    }
    else{
        if (function == 0) {
            [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lld",[[self.publicData objectAtIndex:0] aid]] forKey:@"lastStatusId"];
        }
        else if (function == 1) {
            [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lld",[[self.publicData objectAtIndex:0] aid]] forKey:@"lastMentionId"];
            [self resetCountWithType:2];
            
        }
        else if (function == 3){
            [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lld",[[self.publicData objectAtIndex:0] aid]] forKey:@"lastCommentId"];
            [self resetCountWithType:1];
        }
        [listView reloadData];
    }
    
    [self refreshFans];
    [self checkForNewStatus];
    
    
    [progress stopAnimation:nil];
    
}

- (NSArray *) getTimelineArrayWithCacheType:(NSUInteger) cacheType {
    
    NSArray * timelineArray;
    
    switch (cacheType) {
        case FollowingTimelineCacheType:
            if (cacheManager.firstFollowingCall) {
                timelineArray = [self getFriendsTimeline:0 maxId:0 count:20 page:1];
                
            }
            else{
                timelineArray = [self getFriendsTimeline:[cacheManager.lastFollowingStatusID longLongValue] maxId:0 count:0 page:1];
            }
            break;
        case MentionsTimelineCacheType:
            if (cacheManager.firstMentionsCall) {
                timelineArray = [self getMentions:0 maxId:0 count:20 page:1];
                
            }
            else{
                timelineArray = [self getMentions:[cacheManager.lastMentionStatusID longLongValue] maxId:0 count:0 page:1];
            }
            break;
        case SelfTimelineCacheType:
            if (cacheManager.firstSelfCall) {
                timelineArray = [self getUserTimeline:0 userId:0 screenName:nil sinceId:0 maxId:0 count:20 page:1];
            }
            else{
                timelineArray = [self getUserTimeline:0 userId:0 screenName:nil sinceId:[cacheManager.lastSelfStatusID longLongValue] maxId:0 count:0 page:1];
            }
            break;
        case CommentTimelineCacheType:
            if (cacheManager.firstCommentCall) {
                timelineArray = [self getCommentsTimeline:0 maxId:0 count:20 page:1];
            }
            else{
                timelineArray = [self getCommentsTimeline:[cacheManager.lastCommentStatusID longLongValue] maxId:0 count:0 page:1];
                
            }
            break;
            
        default:
            break;
    }
    
    return timelineArray;
    
}

- (void) loadNextPageStatus{
    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    if (!lastAppendStatusTime) {
        lastAppendStatusTime = [NSDate dateWithTimeIntervalSinceNow:-3];
    }
    if ([lastAppendStatusTime timeIntervalSinceNow] < -3) {
        NSUInteger function = [tabTable selectedRow];
        
        dispatch_async(concurrentQueue, ^{
            NSArray * timelineArray;
            switch (function) {
                case 0:
                    timelineArray = [self getFriendsTimeline:0 maxId:[cacheManager.endFollowingStatusID longLongValue]-1 count:20 page:1];
                    
                    break;
                case 1:
                    timelineArray = [self getMentions:0 maxId:[cacheManager.endMentionStatusID longLongValue]-1 count:20 page:1];
                    
                    break;
                case 2:
                    if (_tabTable.isUserViewMode == YES) {
                        int nextpage = (int)[[self publicData] count]/20 + 1;
                        self.publicData = [self.publicData arrayByAddingObjectsFromArray:[self getUserTimeline:0 userId:[(User *)[[[self publicData] objectAtIndex:0] user] uid] screenName:nil sinceId:0 maxId:0 count:20 page:nextpage]];
                        NSLog(@"aftercount:%ld",[[self publicData] count]);
                    }
                    else{
                        timelineArray = [self getUserTimeline:0 userId:0 screenName:nil sinceId:0 maxId:[cacheManager.endSelfStatusID longLongValue]-1 count:20 page:1];
                    }
                    
                    break;
                case 3:
                    timelineArray = [self getCommentsTimeline:0 maxId:[cacheManager.endCommentStatusID longLongValue]-1 count:20 page:1];
                    break;
                default:
                    return ;
                    break;
            }
            dispatch_async(mainQueue, ^{
                if (!_tabTable.isUserViewMode) {
                    [cacheManager appendStatusesForTimelineCache:(function+1) withArray:timelineArray];
                }
                [listView reloadData];
            });
        });
        lastAppendStatusTime = [NSDate dateWithTimeIntervalSinceNow:0];
    }
}

- (void) refreshStatusWithFunction: (NSInteger) function Page:(NSInteger)pages{
    
    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    NSUInteger timelineCacheType = function + 1;
    
	NSMutableArray *cache;
	if (timelineCacheType == FollowingTimelineCacheType) {
		cache = cacheManager.followingStatusCache;
        _tabTable.isUserViewMode = NO;
	} else if (timelineCacheType == MentionsTimelineCacheType) {
		cache = cacheManager.mentionsStatusCache;
        _tabTable.isUserViewMode = NO;
	} else if (timelineCacheType == CommentTimelineCacheType) {
		cache = cacheManager.commentStatusCache;
        _tabTable.isUserViewMode = NO;
	} else if (timelineCacheType == SelfTimelineCacheType) {
		cache = cacheManager.selfStatusCache;
	}
    
    if ( function!=4 && [cache count] > 0 && !_tabTable.isUserViewMode ) {
        self.publicData = cache;
        [listView reloadData];
    }
    dispatch_async(concurrentQueue, ^{
        [progress startAnimation:nil];
        if (_tabTable.isUserViewMode == YES) {
            self.publicData = [self getUserTimeline:0 userId:[(User *)[[[self publicData] objectAtIndex:0] user] uid] screenName:nil sinceId:0 maxId:0 count:20 page:(int)pages];
        }
        else if(function == 4){
            self.publicData = [self getPublicTimeline:20];
        }
        else{
            [cacheManager setStatusesForTimelineCache:timelineCacheType withArray:[self getTimelineArrayWithCacheType:timelineCacheType]];
        }
        [progress stopAnimation:nil];
        if (function == 1) {
            [self resetCountWithType:2];
        }
        else if (function == 3){
            [self resetCountWithType:1];
        }
        dispatch_sync(mainQueue, ^{
            
            if (_tabTable.isUserViewMode == NO && function != 4) {
                self.publicData = cache;
            }
            if(function == [tabTable selectedRow]){
                [listView reloadData];
                [listView reloadData];
            }
            [self checkForNewStatus];
        });
    });
    
    [tabTable selectRowIndexes:[NSIndexSet indexSetWithIndex:function] byExtendingSelection:NO];

}




- (void) refreshFriendsStatusWithUserid:(int) userId Page:(int)pages{
    [progress startAnimation:nil];
    [tabTable selectRowIndexes:[NSIndexSet indexSetWithIndex:2] byExtendingSelection:NO];
    for (int i=0; i<5; i++) {
        self.publicData = [self getUserTimeline:0 userId:userId screenName:nil sinceId:0 maxId:0 count:20 page:pages];
        
        if([self.publicData count] == 0){
            NSLog(@"%d try,getError!",i+1);
        }
        else{
            break;
        }
        
    }
    if([self.publicData count] == 0){
        NSAlert *alert = [NSAlert alertWithMessageText:@"发生了一点错误" defaultButton:@"知道了" alternateButton:nil otherButton:nil informativeTextWithFormat:@"获取数据超时！",nil];
        [alert runModal];
        [alert autorelease];
    }
    else{
        
        _tabTable.isUserViewMode = YES;
        [listView reloadData];
        
    }
    
    [progress stopAnimation:nil];
    
}

- (void) refreshStatusWithFunctionOLD: (NSInteger) function Page:(NSInteger)pages{
    [progress startAnimation:nil];
    //dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_async(mainQueue, ^{
        for (int i=0; i<5; i++) {
            if(function == 0){
                if (cacheManager.firstFollowingCall) {
                    [cacheManager.followingStatusCache setArray:[self getFriendsTimeline:0 maxId:0 count:20 page:1]];
                    NSLog(@"didfirstFollowingCall");
                    cacheManager.firstFollowingCall = NO;
                }
                else{
                    NSArray * newStatus = [self getFriendsTimeline:[cacheManager.lastFollowingStatusID longLongValue] maxId:0 count:0 page:1];
                    NSLog(@"%@",cacheManager.lastFollowingStatusID);
                    [cacheManager setStatusesForTimelineCache:FollowingTimelineCacheType withArray:newStatus];
                }
                
                if ([cacheManager.followingStatusCache count] > 0) {
                    self.publicData = cacheManager.followingStatusCache;
                }
                
                [tabTable selectRowIndexes:[NSIndexSet indexSetWithIndex:0] byExtendingSelection:NO];
            }
            else if(function == 1){
                self.publicData = [self getMentions:0 maxId:0 count:20 page:(int)pages];
                [tabTable selectRowIndexes:[NSIndexSet indexSetWithIndex:1] byExtendingSelection:NO];
            }
            else if(function == 2){
                if (_tabTable.isUserViewMode == YES) {
                    self.publicData = [self getUserTimeline:0 userId:[(User *)[[[self publicData] objectAtIndex:0] user] uid] screenName:nil sinceId:0 maxId:0 count:20 page:(int)pages];
                }
                else{
                    self.publicData = [self getUserTimeline:0 userId:0 screenName:nil sinceId:0 maxId:0 count:20 page:(int)pages];
                }
            }
            else if(function == 3){
                self.publicData = [self getCommentsTimeline:0 maxId:0 count:20 page:(int)pages];
                [tabTable selectRowIndexes:[NSIndexSet indexSetWithIndex:3] byExtendingSelection:NO];
            }
            else{
                return;
            }
            
            if([self.publicData count] == 0){
                NSLog(@"%d try,getError!",i+1);
            }
            else{
                break;
            }
            
        }
        
        
        if([self.publicData count] == 0){
            NSAlert *alert = [NSAlert alertWithMessageText:@"发生了一点错误" defaultButton:@"知道了" alternateButton:nil otherButton:nil informativeTextWithFormat:@"获取数据超时！",nil];
            [alert runModal];
            [alert autorelease];
        }
        else{
            if (pages == 1) {
                if (function == 0) {
                    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lld",[[self.publicData objectAtIndex:0] aid]] forKey:@"lastStatusId"];
                }
                else if (function == 1) {
                    //[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lld",[[self.publicData objectAtIndex:0] aid]] forKey:@"lastMentionId"];
                    [self resetCountWithType:2];
                }
                else if (function == 3){
                    //[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lld",[[self.publicData objectAtIndex:0] aid]] forKey:@"lastCommentId"];
                    [self resetCountWithType:1];
                }
            }
            [listView reloadData];
        }
    });
    [self refreshFans];
    [self checkForNewStatus];
    [progress stopAnimation:nil];
    
    
}



#pragma mark -
#pragma mark OtherMethod

- (void)scrollToTop:(id)sender{
    NSPoint newScrollOrigin;
    
    // assume that the scrollview is an existing variable
    if ([[listView documentView] isFlipped]) {
        newScrollOrigin=NSMakePoint(0.0,0.0);
    } else {
        newScrollOrigin=NSMakePoint(0.0,NSMaxY([[listView documentView] frame])
                                    -NSHeight([[listView contentView] bounds]));
    }
    
    [[listView documentView] scrollPoint:newScrollOrigin];
    
}

- (void)scrollDownARow{
    
    if ([[[listView visibleCells] lastObject] row] == 19) {
        [_tabTable nextPage:self];
    }
    else{
        if ([[[listView visibleCells] lastObject] row] == 18) {
            [listView scrollRowToVisible:19];
        }
        else{
            [listView scrollToRow:[[[listView visibleCells] objectAtIndex:0] row] + 1];   
        }
    }
}
- (void) scrollUpARow{
    if([[[listView visibleCells] objectAtIndex:0] row] == 0){
        [listView scrollToRow:0];
    }
    else{
        [listView scrollRowToVisible:[[[listView visibleCells] objectAtIndex:0] row]-1];
    }
    
}

- (void) viewImageInCurrentRow{
    
    [self viewImageInRow:[[[listView visibleCells] objectAtIndex:0] row]];
    
}

- (void) selectTabByIndex:(int) index{
    
    [tabTable deselectAll:self];
    [tabTable selectRowIndexes:[NSIndexSet indexSetWithIndex:index] byExtendingSelection:NO];
    
}


@end